package com.itheima.test.TCP.threadpool;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class MyRunnable implements Runnable {
    private Socket socket = new Socket();

    public MyRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            //创建网络中的流
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            //本地文件流,UUID生成不重复的文件名称
            bos = new BufferedOutputStream(new FileOutputStream("day020\\" + UUID.randomUUID().toString() + ".txt"));
            //读写数据
            int ch;
            while ((ch = bis.read()) != -1) {
                bos.write(ch);//将网络中的数据写到本地
            }
            //传回上传成功
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源,网络中的流不用管,关本地的流
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //serverSocket.close();不需要关闭服务器
        }
    }
}
